package hhh.app.presenter.model.productdetail;

import android.graphics.Color;
import android.support.design.widget.NavigationView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import hhh.app.R;
import hhh.app.common.Code;
import hhh.app.common.DensityUtil;
import hhh.app.common.L;
import hhh.app.data.bean.Product;
import hhh.app.data.bean.ProductDiscount;
import hhh.app.data.bean.ProductImage;
import hhh.app.data.bean.ProductOption;
import hhh.app.data.bean.Review;
import hhh.app.presenter.App;
import hhh.app.presenter.di.component.ProductComponent;
import hhh.app.presenter.ui.base.BaseActivity;
import hhh.app.presenter.ui.view.CustomItemView;
import hhh.app.presenter.ui.view.MyScrollView;
import hhh.app.presenter.ui.view.PinLunView;
import hhh.app.presenter.ui.view.PullUpToLoadMore;

/**
 * Created by hhh on 2016/10/31.
 */
public class ProductDetailActivity extends BaseActivity implements ProductDetailContract.IProductDetailView,PullUpToLoadMore.TopViewScrollListener
{
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.navigation_view)
    NavigationView navigationView;

    @BindView(R.id.buy_btn)
    Button buyBtn;

    @BindView(R.id.pullloadmore)
    PullUpToLoadMore pullUpToLoadMore;

    @BindView(R.id.detail_scrollview)
    MyScrollView detailScrollview;
    @BindView(R.id.parent_layout)
    RelativeLayout parentLayout;
    @BindView(R.id.buy)
    RelativeLayout buyTopLayout;
    @BindView(R.id.rollview)
    RollPagerView rollview;

    @BindView(R.id.buy_price)
    TextView buyPrice;
    @BindView(R.id.buy_oldprice)
    TextView buyOldprice;

    @BindView(R.id.discount)
    CustomItemView discount;
    @BindView(R.id.option)
    CustomItemView option;
    @BindView(R.id.pinlun)
    PinLunView pinLunView;

    @BindView(R.id.detail_linearlayout)
    LinearLayout detailLinearLayout;

    private WebView webView;

    private int btHeight;

//    public int getPid() {
//        return pid;
//    }

    private Product product;
//    private int pid = -1;
    private int displayHeight;
    private int displayWidth;

    private PopupWindow popupWindow;

    private List<String> titleList=new ArrayList<String>();
    private List<View> viewList=new ArrayList<View>();

    private List<ProductImage> productImages=new ArrayList<ProductImage>();
    private RollAdapter rollAdapter;

    //    private ProductDetailFragment productDetailFragment;
    @Inject
    ProductDetailPresenter productDetailPresenter;

    protected void init() {
        getComponent().inject(this);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);

//        pullUpToLoadMore.setscroll(this);
        pullUpToLoadMore.setTopViewScrollListener(this);
        displayHeight = getWindowManager().getDefaultDisplay().getHeight();
        displayWidth = getWindowManager().getDefaultDisplay().getWidth();

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
//        btHeight=DensityUtil.dip2px(this,(180-64));//bannerHeight-toolbarHeight;
        btHeight= DensityUtil.dip2px(this,116);

        mToolbar.setTitleTextColor(Color.TRANSPARENT);
        mToolbar.setBackgroundColor(Color.TRANSPARENT);

        navigationView.setCheckedItem(R.id.nav_setting);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                return false;
            }
        });

//        pid = getIntent().getIntExtra("pid", -1);
        product= (Product) getIntent().getBundleExtra("product").get("product");

        init_rollview();
//        init_discount();
//        init_review();
        init_webview();

        productDetailPresenter.attachView(this);
        int pid=product.getId();
        productDetailPresenter.loadProductDiscounts(pid);
        productDetailPresenter.loadProductImages(pid);
        productDetailPresenter.loadProductReviews(pid);
    }

    private void init_rollview(){
        rollview.setPlayDelay(1000);
        rollview.setAnimationDurtion(500);
        rollAdapter=new RollAdapter(productImages);
        rollview.setAdapter(rollAdapter);
        rollview.setHintView(new ColorPointHintView(this, Color.YELLOW, Color.WHITE));
    }

//    private void init_review(){
//        List<Review> reviews=new ArrayList<Review>();
//        reviews.add(new Review());
//        reviews.add(new Review());
//        reviews.add(new Review());
//        pinLunView.setData(reviews);
//    }

    private void init_webview() {
        String url= Code.productUrl +"getproductdetail/"+product.getId();
        webView=new WebView(this);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
        detailLinearLayout.addView(webView, LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
    }


    public ProductComponent getComponent() {
        return ((App) getApplication()).getProductComponent();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.drawlayout_detail;
    }


    private void showPopup(View v, View contentView) {
        if (popupWindow == null) {
            popupWindow = new PopupWindow(contentView, displayWidth, displayHeight/2);
            popupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
            popupWindow.setFocusable(false);
            popupWindow.setOutsideTouchable(true);

            final String[] notions=getResources().getStringArray(R.array.notions);
//            ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,notions);

            View listView= contentView.findViewById(R.id.dialog_list);
            if(listView instanceof ListView){
                ((ListView) listView).setAdapter(new com.zhy.adapter.abslistview.CommonAdapter<String>(this,R.layout.layout_list_item2, Arrays.asList(notions)) {
                    @Override
                    protected void convert(com.zhy.adapter.abslistview.ViewHolder viewHolder, String item, int position) {
                        viewHolder.setText(R.id.item2_title,item);
                    }
                });


            }

            View btn=contentView.findViewById(R.id.dialog_button);
            if(btn instanceof Button){
                ((Button)btn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupWindow.dismiss();
                    }
                });
            }
        }
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void showProductDetail(Product p) {

    }

    @Override
    public void showProductImages(List<ProductImage> list) {
        productImages.clear();
        if(!list.isEmpty()) {
            productImages.addAll(list);
        }else{
            ProductImage p=new ProductImage();
            p.setImage(product.getImage());
            productImages.add(p);
        }
        rollAdapter.notifyDataSetChanged();
    }

    @Override
    public void showProductDiscounts(List<ProductDiscount> list) {
        StringBuffer sb=new StringBuffer();
        SimpleDateFormat s=new SimpleDateFormat("M-dd");
        int count=list.size();
        for (int i=0;i<count;i++) {
            ProductDiscount p=list.get(i);
            sb.append(p.getPrice())
                    .append(" ")
                    .append(s.format(p.getDate_start()))
                    .append(" 至 ")
                    .append(s.format(p.getDate_end()));
            if(i<count-1){
                sb.append("\n");
            }
        }
        discount.setLabel(sb.toString());
    }

    @Override
    public void showProductOptions(List<ProductOption> list) {

    }

    @Override
    public void showProductReviews(List<Review> list) {
        pinLunView.setData(list);
        //pinLunView.invalidate();
    }

    @OnClick({R.id.discount, R.id.option})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.discount:
                break;
            case R.id.option:
                View content= getLayoutInflater().inflate(R.layout.dialog_list,null);
                showPopup(parentLayout,content);
                break;
        }
    }

    @Override
    public void onTopViewScrollListener(int scrollY) {
        L.d("scrollY:"+scrollY+",btHeight:"+btHeight);
            if (scrollY <= 0) {
                mToolbar.setTitleTextColor(Color.TRANSPARENT);
                mToolbar.setBackgroundColor(Color.TRANSPARENT);
            } else if (scrollY > 0 && scrollY < btHeight) {
                float scale = (float) scrollY / btHeight;
                float alpha = (255 * scale);
                mToolbar.setTitleTextColor(Color.argb((int) alpha, 255, 255, 255));
                mToolbar.setBackgroundColor(Color.argb((int) alpha, 63, 81, 181));
            } else {
                mToolbar.setBackgroundColor(Color.argb(255, 63, 81, 181));
            }

    }

    private class RollAdapter extends StaticPagerAdapter {
//        private int[] imgs = {R.mipmap.yanjing7xq3, R.mipmap.yanjing91xq1, R.mipmap.yanjing91xq3, R.mipmap.yanjing10xq3};
//
//        @Override
//        public View getView(ViewGroup container, int position) {
//            ImageView view = new ImageView(container.getContext());
//            view.setImageResource(imgs[position]);
//            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
//            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//            return view;
//        }

        private List<ProductImage> urls;

        public RollAdapter(List<ProductImage> urls) {
            this.urls = urls;
        }

        @Override
        public View getView(ViewGroup container, int position) {
            ImageView view=new ImageView(container.getContext());
            Picasso.with(container.getContext()).load(Code.baseImageUrl+urls.get(position).getImage()).into(view);
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            return view;
        }

        @Override
        public int getCount() {
            return urls.size();
        }
    }

    private class MyWebViewClient extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            return true;
        }
    }
}
